package root.agent.demo.invoke;

import io.micrometer.observation.ObservationFilter;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.advisor.MessageChatMemoryAdvisor;
import org.springframework.ai.chat.memory.InMemoryChatMemory;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;
import root.agent.demo.advisors.MyLogAdvisor;

import java.util.concurrent.atomic.AtomicBoolean;

import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_CONVERSATION_ID_KEY;
import static org.springframework.ai.chat.client.advisor.AbstractChatMemoryAdvisor.CHAT_MEMORY_RETRIEVE_SIZE_KEY;

@Component
@Slf4j
public class SpringAiInvokeV2 {
    @Resource
    public ChatModel dashScopeChatModel;
    @Resource
    private  InMemoryChatMemory inMemoryChatMemory;


    public Flux<String> getChatStream(String text) {
        ChatClient client = ChatClient.builder(dashScopeChatModel)
                .defaultSystem("你是一个情感博主专家，专门可以开导年轻人").build();

        return client.prompt().user(text).stream().content();
    }

    record MyResponse(String result) {

    }

    public void chat(){
        ChatClient client = ChatClient.builder(dashScopeChatModel)
                .defaultSystem("你是一个情感博主专家，专门可以开导年轻人").build();

        ChatClient.CallResponseSpec response = client.prompt().user("张三失恋了").call();
        System.out.println(response.chatResponse().getResult());

    }

    public void chatWithObject(){
        ChatClient client = ChatClient.builder(dashScopeChatModel)
                .defaultSystem("你是一个情感博主专家，专门可以开导年轻人").build();

        MyResponse response = client.prompt().user("张三失恋了").call().entity(MyResponse.class);
        System.out.println(response.result);
    }

    public void chatWithFlux() throws InterruptedException {
        ChatClient client = ChatClient.builder(dashScopeChatModel)
                .defaultSystem("你是一个情感博主专家，专门可以开导年轻人").build();

        Flux<String> fluxString = client.prompt().user("张三失恋了").stream().content();
        AtomicBoolean flag = new AtomicBoolean(false);
        fluxString.subscribe(content->{
            System.out.print(content);
            try {
                Thread.sleep(50);  // 添加短暂延迟以增强打字机效果
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        },error->{
            System.out.println("Error: " + error.getMessage());
        },()->{
            flag.set(true);
        });
        while (true){
           if(flag.get()){
               break;
           }
        }
    }

    /**
     * 带记忆的聊天
     * */
    public void chatWithChatMemory(String message,String chatId){
        ChatClient client = ChatClient.builder(dashScopeChatModel)
                .defaultSystem("你是一个情感博主专家，专门可以开导年轻人")
                .defaultAdvisors(new MessageChatMemoryAdvisor(inMemoryChatMemory)).build();

        ChatClient.CallResponseSpec called = client.prompt().user(message).advisors(advisorSpec -> {
            advisorSpec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId).param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 1);
        }).call();
        log.info(String.valueOf(called.chatResponse().getResult()));
    }

    /**
     * 带记忆的聊天
     * */
    public void chatWithChatMemoryAndLog(String message, String chatId){
        ChatClient client = ChatClient.builder(dashScopeChatModel)
                .defaultSystem("你是一个情感博主专家，专门可以开导年轻人")
                .defaultAdvisors(new MessageChatMemoryAdvisor(inMemoryChatMemory)).build();

        ChatClient.CallResponseSpec called = client.prompt().user(message).advisors(advisorSpec -> {
            advisorSpec.param(CHAT_MEMORY_CONVERSATION_ID_KEY, chatId).param(CHAT_MEMORY_RETRIEVE_SIZE_KEY, 1);
        }).advisors(new MyLogAdvisor()).call();
        log.info(String.valueOf(called.chatResponse().getResult()));
    }


}
